import usePermissionStore from '@/store/modules/permission'
import useUserStore from '@/store/modules/user'
import router from '..'

// 免登录路由白名单
const whiteRoutes: string[] = ['/login', '/404', '/403', '/500', '/loginFromErp', '/providerLogin', '/supplierLogin']

function usePermissionGuard() {
  router.beforeEach(async (to) => {
    if (whiteRoutes.includes(to.path)) {
      return true
    }
    const userStore = useUserStore()
    if (!userStore.token) {
      return {
        path: '/login',
        query: { redirect: to.fullPath },
      }
    }
    if (!userStore.isLoadAuth) {
      userStore.getUserAuthCode()
    }
    const permissionStore = usePermissionStore()
    const isEmptyRoute = permissionStore.isEmptyPermissionRoute()
    if (isEmptyRoute) {
      await permissionStore.initPermissionRoute()
      return { ...to, replace: true }
    }
    return true
  })
}

export default usePermissionGuard
